package com.pickup.kafka.config;

import com.pickup.pool.ThreadPoolUtil;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.listener.ContainerProperties;

import java.util.Collections;
import java.util.Objects;
import java.util.Properties;

public class MyConsumer {
    private static final KafkaConsumer<String, String> consumer;

    static {
        Properties properties = new Properties();
        properties.put("bootstrap.servers", "192.168.0.10:9092");
        properties.put("group.id", "group.id");
        properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put("enable.auto.commit", "false");


        consumer = new KafkaConsumer<>(properties);
    }

    private static void consumerTest() {
        //订阅topic
        consumer.subscribe(Collections.singleton("ChatMsg"));

        try {
            while (true) {
                //在100ms内等待Kafka的broker返回数据.超市参数指定poll在多久之后可以返回，不管有没有可用的数据都要返回
                ConsumerRecords<String, String> records = consumer.poll(10000);
                for (ConsumerRecord<String, String> record : records) {
                    if (Objects.equals(record.key(), "老许")) {
                        consumer.commitSync();
                        //System.out.println(("******************: " + "topic:" + record.topic() + " " + "offset:" + record.offset() + " " + "key:" + record.key() + " " + "value:" + record.value()));
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("error:" + e);
        } finally {
            consumer.close();
        }

    }

    public static void main(String[] args) {
        ThreadPoolUtil threadPoolUtil = new ThreadPoolUtil();
        threadPoolUtil.getExecutorPool().execute(() -> {
            for (int i = 0; i < 10; i++) {
                consumerTest();
            }
        });

    }


}